<?php
/**
 * Created by PhpStorm.
 * User: qufan
 * Date: 2016/12/16 0016
 * Time: 0:33
 */

namespace Home\Controller;


class InfoManageController extends HomeController
{
    public function index($tab = 1){
        $this->meta_info = '信息管理';
        $this->showTab = $tab;
        $this->display();
    }

    /**
    *add : 搜索错误问题及添加排序
    *user：边个懂
    *time：20170518
    **/
    public function infoList($limit, $offset, $searchOption, $search = null,$rder){
        $field = 'm.*, su.real_name as send_real_name, ru.real_name as receive_real_name';
        $where2 = array();
        if (!empty($search)){
            switch ($searchOption){
                case 1:
                    $where['title'] = array('like', "%{$search}%");
                    break;

                case 2:
                    if($search == -1 || $search == '中心端'){
                        $where['send_user_id'] = 0;
                    }else{
                        $needHaving = true;
                        $where2['send_real_name'] = array('like', "%{$search}%");
                    }
                    break;

                case 3:
                    if($search == -1 || $search == '中心端'){
                        $where['receive_user_id'] = 0;
                    }else{
                        $needHaving = true;
                        $where2['receive_real_name'] = array('like', "%{$search}%");
                    }
                    break;
            }
        }
        if(!empty($this->uids)){
            $where['_string'] = "m.send_user_id in(".implode(',', $this->uids).") OR m.receive_user_id in(".implode(',', $this->uids).")";
        }

        $where['m.center_delete'] = 0;
        $model = M('Message');          
        $order = ' send_time '.$rder;
        if($needHaving){
            $subQuery = M('Message')->alias('m')->join('user su on m.send_user_id=su.user_id','left')->join('user ru on m.receive_user_id = ru.user_id','left')->where($where)->field($field)->buildSql();
            $record = $model->table($subQuery. ' a')->where($where2)->order($order)->limit($offset, $limit)->select();
            $total_count = $model->table($subQuery . ' a')->where($where2)->count();
        }else{
            $record = M('Message')->alias('m')->join('user su on m.send_user_id=su.user_id', 'left')->join('user ru on m.receive_user_id = ru.user_id', 'left')->where($where)->field($field)->order($order)->limit($offset, $limit)->select();
            $total_count = M('Message')->alias('m')->where($where)->count();
        }

        foreach ($record as $key => $value){
            if (empty($value['receive_real_name'])){
                $record[$key]['receive_real_name'] = '中心端';
            }
            if (empty($value['send_real_name'])){
                $record[$key]['send_real_name'] = '中心端';
            }
            $record[$key]['enclosures'] = M('MessageEnclosure')->where("message_id = {$value['message_id']}")->select();
        }

        $result['rows'] = $record;
        $result['total'] = $total_count;
        $this->ajaxReturn($result);
    }

    public function getChatList(){

        $where['r.platform'] = 2;
        $where['_string'] = '(m.receive_user_id = 0) or m.message_id is null';
        if(!empty($this->uids)){
            $where['u.user_id'] = array('in', $this->uids);
        }
        $field = 'u.*';
        $chat_users = M('User')->alias('u')->distinct('u.user_id')
            ->join('role r on u.role_id=r.role_id')
            ->join('message m on u.user_id=m.send_user_id', 'left')->order('m.send_time desc')->field($field)->where($where)->select();
        foreach ($chat_users as &$user){
            $map['receive_user_id'] = 0;
            $map['send_user_id'] = $user['user_id'];
            $map['state'] = 1;
            $res = M('Message')->where($map)->find();
            if($res){
                $user['unread'] = 1;
            }else{
                $user['unread'] = 0;
            }
        }
        $this->sucessJson($chat_users);

    }

    public function getMessageByUserId($user_id){
        if(!empty($this->uids)){
            $where['_string'] = "send_user_id in(".implode(',', $this->uids).") OR receive_user_id in(".implode(',', $this->uids).")";
        }
        $where['send_user_id'] = 0;
        $where['receive_user_id'] = $user_id;
        $map['_complex'] = $where;
        $map['_string'] = "send_user_id={$user_id} and receive_user_id=0";
        $map['_logic'] = 'or';
        $messages = D('Message')->where($map)->order('send_time asc')->select();
        D('Message')->where($map)->setField('state', 2);
        $this->sucessJson($messages);
    }

    public function map($message_id){
        $message = D('Message')->find($message_id);
        if($message){
            $this->message = $message;
            $this->display();
        }else{
            $this->error('找不到指定消息');
        }
    }

    public function getMessagePageByUserId($user_id, $startCtime = 0,  $pageCount = 10){
        if(!empty($this->uids)){
            $where['_string'] = "send_user_id in(".implode(',', $this->uids).") OR receive_user_id in(".implode(',', $this->uids).")";
        }
        $where['send_user_id'] = 0;
        $where['receive_user_id'] = $user_id;
        empty($startCtime) && $startCtime = time_format(NOW_TIME);
        $map['_complex'] = $where;
        $map['_string'] = "send_user_id={$user_id} and receive_user_id=0";
        $map['_logic'] = 'or';
        $condition['_complex'] = $map;


        $condition['send_time'] = array('lt', $startCtime);
        $messages = D('Message')->where($condition)->order('send_time desc')->limit($pageCount)->select();
        $ids = array_column($messages, 'message_id');
        $where2['message_id'] = array('in', $ids);
        $records = D('MessageEnclosure')->where($where2)->select();
        $ref = array();
        foreach ($records as $record){
            $record['enclosure_url'] = substr($record['enclosure_url'],0,2) . '/' .$record['enclosure_url'];
            if (isset($ref[$record['message_id']])){
                $ref[$record['message_id']] = array();
            }
            $ref[$record['message_id']][] = $record;
        }
        foreach ($messages as &$message){

            if(isset($ref[$message['message_id']])){
                $message['enclosure'] = $ref[$message['message_id']];
            }
        }
        D('Message')->where($condition)->setField('state', 2);
        $this->sucessJson($messages);
    }

    public function sendTextMessage(){
        $data['send_user_id'] = 0;
        $data['receive_user_id'] = $_POST['receive_user_id'];
        $data['remark'] = UID;
        $data['content'] = $_POST['content'];
        $data['send_time'] = time_format(NOW_TIME);
        $data['state'] = 1;
        $data['title'] = '来自中心端';
        $model = D('Message');
        if($model->create($data)){
            $id = $model->add($data);
            if($id > 0){

                $this->sucessJson();
            }
        }
        $this->errorJson('发送失败');
    }
    /**
     * [sendImgMessage description]
     * @return [type] [description]
     * add : 发送doc txt 格式存储状态为4
     * user: 边个懂
     * time: 20170524
     */
    public function sendImgMessage(){
        $data['send_user_id'] = 0;
        $data['receive_user_id'] = $_POST['receive_user_id'];
        $data['title'] = '附件';
        $realname = session('user_auth.realname');
        $data['content'] = "由中心端{$realname}发送";
        $data['send_time'] = time_format(NOW_TIME);
        $data['state'] = 1;
        $model = D('Message');
        $modelEnclosure = D('MessageEnclosure');
        if($model->create($data)){
            $id = $model->add($data);
            if($id > 0){
                $item['file_size'] = $_POST['filesize'] / 1000;
                $item['enclosure_formerly'] = $_POST['filename'];
                $item['enclosure_url'] = $_POST['img_path'];
                $item['message_id'] = $id;
                $exist = array('txt','doc');
                $suffix = end(explode('.',$item['enclosure_url']));
                in_array($suffix,$exist) ? $item['enclosure_type'] = 4 : $item['enclosure_type'] = 1;
                if($modelEnclosure->create($item)) {
                    $meid = $modelEnclosure->add();
                    if($meid){
                        $item['enclosure_url'] = substr($item['enclosure_url'],0,2) . '/' .$item['enclosure_url'];
                        $this->sucessJson($item);
                    }
                }

            }
        }
        $this->errorJson('发送失败');
    }

    public function deleteMsg(){
        $ids = $_POST['selectedIds'];
        $map['message_id'] = array('in', $ids);
        $data['center_delete'] = 1;
        $data['deleteUserId'] = UID;
        $model = D('Message');
        if(false !== $model->where($map)->save($data)){
            logOperation('信息管理','删除消息');
            $this->sucessJson();
        }else{
            $this->errorJson($model->getError());
        }

    }


}